package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.naming.Name;
import java.math.BigDecimal;
import java.security.GeneralSecurityException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    // TODO 用户名未传递过来
    @Transactional
    @Override
    public OrderSubmitVO placeAnOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //业务异常处理

        //判断地址簿是否为空
        AddressBook addressBook = addressBookMapper.getAddressById(ordersSubmitDTO.getAddressBookId());
        if (addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list==null || list.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        //设置订单信息
        //获取地址
        String address =  addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        orders.setAddress(address);

        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(orders.PENDING_PAYMENT);
        orders.setPayStatus(orders.UN_PAID);
        orders.setPhone((addressBook.getPhone()));
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        //向订单表插入一条数据
        ordersMapper.insert(orders);

        //向订单明细表插入n条数据
        List<OrderDetail> orderList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderList.add(orderDetail);
        }

        orderDetailMapper.insert(orderList);
         //清空当前购物车信息
        shoppingCartMapper.deleteAllById(BaseContext.getCurrentId());
        //封装成vo对象返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public void payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
        //-----------------------------------



        Orders orders = Orders.builder()
                .number(ordersPaymentDTO.getOrderNumber())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        ordersMapper.orderPay(orders);

        //使用websocket向客户端浏览器推送消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",1);  //1表示来单提醒，2表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号"+ordersPaymentDTO.getOrderNumber());
        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = ordersMapper.pageList(ordersPageQueryDTO);

        List<OrderVO> orderVOS = new ArrayList<>();
        if (page!=null && page.size()>0){
            for (Orders order : page) {
                //获取订单id
                Long orderId = order.getId();
                //获取订单明细
                List<OrderDetail> orderDetail = orderDetailMapper.getDetailById(orderId);

                //将订单明细添加进集合中
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);
                orderVO.setOrderDetailList(orderDetail);
                orderVOS.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),orderVOS);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {

        OrderVO orderVO = new OrderVO();

        //获取订单数据
        Orders order = ordersMapper.getOrderById(id);
        BeanUtils.copyProperties(order,orderVO);

        //获取订单详情
        List<OrderDetail> detail = orderDetailMapper.getDetailById(id);
        orderVO.setOrderDetailList(detail);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) throws Exception {
        //根据id查询订单
        Orders order = ordersMapper.getOrderById(id);
        //校验订单是否存在
        if (order==null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //校验订单状态，订单状态>2，则派送中，不能取消
        if (order.getStatus()>2){
            throw new  OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单处于待接单状态需要退款
        Orders orders = new Orders();
        order.setId(order.getId());

        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    order.getNumber(), //商户订单号
                    order.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void againOrder(Long id) {
        //根据id查询订单详情
        List<OrderDetail> detailById = orderDetailMapper.getDetailById(id);

        List<ShoppingCart> shoppingCart = new ArrayList<>();
        for (OrderDetail orderDetail : detailById) {
            //将detail添加到购物车中
            ShoppingCart shopping = ShoppingCart.builder()
                    .name(orderDetail.getName())
                    .image(orderDetail.getImage())
                    .userId(BaseContext.getCurrentId())
                    .dishId(orderDetail.getDishId())
                    .setmealId(orderDetail.getSetmealId())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .number(orderDetail.getNumber())
                    .amount(orderDetail.getAmount())
                    .createTime(LocalDateTime.now())
                    .build();
            shoppingCart.add(shopping);

        }

        //将购物车中的商品添加到数据库中
        shoppingCartMapper.insertBatch(shoppingCart);
    }

    //TODO 用户催单
    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //获取订单信息
        Orders order = ordersMapper.getOrderById(id);
        if (order.getStatus()==2 || order.getStatus()==3){
            HashMap<String, Object> map = new HashMap<>();
            map.put("type",2);
            map.put("orderId",id);
            map.put("content","订单号："+order.getNumber());
            String json = JSON.toJSONString(map);
            webSocketServer.sendToAllClient(json);
        }
    }

    /**
     * 商家查看订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //查询订单信息
        Page<Orders> page = ordersMapper.pageList(ordersPageQueryDTO);

        //查询对应的菜品，封装进vo
        List<OrderVO> orderVOList = getOrderDetail(page);

        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO)  {
        //查询订单
        Orders order = ordersMapper.getOrderById(ordersCancelDTO.getId());

        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        order.setPayStatus(Orders.REFUND);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);

    }

    /**
     * 商家拒绝订单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //获取订单信息
        Orders order = ordersMapper.getOrderById(ordersRejectionDTO.getId());
        //更新订单状态，拒绝原因，取消时间
        order.setStatus(Orders.CANCELLED);
        order.setPayStatus(Orders.REFUND);
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());

        ordersMapper.update(order);
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO lookOrder(Long id) {
        //获取订单信息
        Orders orders = ordersMapper.getOrderById(id);
        //获取订单详细信息
        List<OrderDetail> detail = orderDetailMapper.getDetailById(id);
        //获取菜品字段
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < detail.size(); i++) {

            String name = detail.get(i).getName();
            Integer number = detail.get(i).getNumber();

            if(i == detail.size()-1){
                sb.append(name+"*").append(number);
            }
            sb.append(name+"*").append(number);
        }

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDishes(sb.toString());
        orderVO.setOrderDetailList(detail);
        return orderVO;
    }


    /**
     * 完成订单
     * @param id
     */
    @Override
    public void finishOrder(Long id) {
        Orders order = ordersMapper.getOrderById(id);

        //判断订单是否存在
        if (order==null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //更新订单信息
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);

    }

    /**
     * 查看各个状态的订单
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //统计各个状态订单数量
        int tobeConfirmed = ordersMapper.getStatus(Orders.TO_BE_CONFIRMED);
        int confirmed = ordersMapper.getStatus(Orders.CONFIRMED);
        int deliveryInProgress = ordersMapper.getStatus(Orders.DELIVERY_IN_PROGRESS);

        //封装到vo对象中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(tobeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //判断订单是否存在
        Orders order = ordersMapper.getOrderById(id);
        if (order==null || !order.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Orders orders = Orders.builder()
                .id(order.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        ordersMapper.update(orders);
    }



    //查询对应的菜品，封装进vo
    private List<OrderVO> getOrderDetail(Page<Orders> page){
        List<OrderVO> list = new ArrayList<>();
        for (Orders order : page) {
            List<OrderDetail> detailList = orderDetailMapper.getDetailById(order.getId());

            //获取同一个订单中菜品的名称
            String name = getName(detailList);

            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            orderVO.setOrderDishes(name);

            //通过订单id查询明细
            orderVO.setOrderDetailList(detailList);
            list.add(orderVO);
        }
        return list;
    }
    //获取同一个订单中菜品的名称
    private String getName(List<OrderDetail> detailList){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < detailList.size(); i++) {
            //获取菜品或套餐名字
            String name = detailList.get(i).getName();
            //获取数量
            Integer number = detailList.get(i).getNumber();
            if (i==detailList.size()-1){
                sb.append(name+"*"+number);
                break;
            }
            sb.append(name+"*").append(number).append("*");
        }
        return sb.toString();
    }
}
